
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by dycong on 2017/5/31.
 */
public class ParameterClient {
    private static final Logger log = Logger.getLogger(ParameterClient.class);
    private BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient;

    @Before
    public void init() {
        httpclient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
                .build();
    }

    @Test
    public void listAllLoanBanner2() throws IOException, ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Writer writer = new FileWriter(new File("C:\\Users\\arlain\\Desktop\\隐私\\work2.txt"));
        BufferedWriter bufferedWriter = new BufferedWriter(writer);
        bufferedWriter.newLine();
        bufferedWriter.flush();
        Map<String, Object> bodyMap = new HashMap<String, Object>();
        Calendar today = Calendar.getInstance();
        today.setTime(simpleDateFormat.parse("2019-11-20"));
        double total = 0d;
        while (true) {
            bodyMap.put("selDate", simpleDateFormat.format(today.getTime()));
            String url = "https://employee.samething.org/self-service-api/worktimeHour/queryForWeekHour";
            String result = post(bodyMap, url);
            JSONObject object = JSONObject.fromObject(result);
            double week = object.getDouble("totalCount");
            total += week;
            today.add(Calendar.DAY_OF_YEAR, -7);
            System.out.println("周期： " + today.getTime() + "周： " + week + "总：" + total);
            bufferedWriter.append("周期： " + today.getTime() + "周： " + week + "总：" + total);
            bufferedWriter.newLine();
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }


    }

    @Test
    public void listAllLoanBanner() throws IOException, ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Writer writer = new FileWriter(new File("C:\\Users\\arlain\\Desktop\\隐私\\work.txt"));
        BufferedWriter bufferedWriter = new BufferedWriter(writer);
        bufferedWriter.newLine();
        bufferedWriter.flush();
        Map<String, Object> bodyMap = new HashMap<String, Object>();
        Calendar today = Calendar.getInstance();
        today.setTime(simpleDateFormat.parse("2019-11-20"));

        while (true) {
            bodyMap.put("selDate", simpleDateFormat.format(today.getTime()));
            String url = "https://employee.samething.org/self-service-api/worktimeHour/queryForWeekHour";
            String result = post(bodyMap, url);
            bufferedWriter.append(result);
            bufferedWriter.newLine();
            bufferedWriter.newLine();
            bufferedWriter.flush();
            System.out.println(result);
            today.add(Calendar.DAY_OF_YEAR, -7);
        }


    }


    private String post(Map<String, Object> bodyMap, String url) {
        return execute(url, bodyMap);

    }

    public String execute(String url, Map<String, Object> bodyMap) {
        String result = "";
        List<NameValuePair> valuePairs = new ArrayList<>(bodyMap.size());
        for (Map.Entry<String, Object> m : bodyMap.entrySet()) {
            NameValuePair nvp = new BasicNameValuePair(m.getKey(), m.getValue().toString());
            valuePairs.add(nvp);
        }
        try {
            HttpUriRequest request = RequestBuilder.post()
                    .setUri(new URI(url))
                    .addParameters(valuePairs.toArray(new NameValuePair[bodyMap.size()]))
                    .addHeader("Accept", "application/json, text/plain, */*")
                    .addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7")
                    .addHeader("User-Agent",
                            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36")
                    .addHeader("Accept-Encoding", "gzip, deflate, br")
                    .addHeader("Connection", "Keep-Alive")

                    //todo 请求时携带的Cookie是放在Header里的大哥！cookieStore是接收服务端放置的Cookie的
                    .addHeader(new BasicHeader("Cookie", "JSESSIONID=1315a31d-9d72-4312-be65-d5084dca9af3; route=dafd62f644c85979e9f749f91f1a02cb"))
                    .addHeader(new BasicHeader("Cookie", "_ga=GA1.1.1188565710.1495689275"))
                    .build();

            CloseableHttpResponse response = httpclient.execute(request);
            List<Cookie> cookies = cookieStore.getCookies();

            result = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        } catch (URISyntaxException e) {
            log.error("url error: " + e);
            result = e.getMessage();
        } catch (IOException e) {
            log.error(e);
            result = e.getMessage();
        }
        return result;
    }
}
